import re
import poplib
import time
from email.parser import BytesParser
from email.header import decode_header, make_header
from exchangelib import Credentials, Account, DELEGATE, errors
# 获取 openai 邮件
def get_signup_link(email_name, password, display_to, num_emails=1, sendEmail='noreply@tm.openai.com',max_attempts=2, retry_delay=5):
    attempts = 0
    while attempts < max_attempts:
        try:
            # 设置凭据和连接
            credentials = Credentials(email_name, password)
            account = Account(email_name, credentials=credentials, autodiscover=True, access_type=DELEGATE)

            # 获取指定数量的最新邮件并返回信息列表
            link = None
            for item in account.inbox.all().order_by('-datetime_received')[:num_emails]:
                email_info = {
                    "主题": item.subject,
                    "收件人":item.display_to,
                    "发件人": item.sender.email_address,
                    "时间": item.datetime_received,
                    "正文": item.text_body
                }
                # 提取链接地址的正则表达式
                url_pattern = r'<(https?://\S+)>'
                # 提取电子邮件中的链接地址
                urls = re.findall(url_pattern, item.text_body)
                if urls and item.display_to == display_to:
                    link = urls[0]
                    # 删除邮件
                    # item.delete()

            return link
        except errors.AutoDiscoverFailed:
            print("自动发现失败，请检查邮箱地址和密码是否正确，或者尝试手动设置连接信息。")
        except errors.ErrorFolderNotFound:
            print("找不到邮件文件夹，请确认邮箱中存在邮件。")
        except Exception as e:
            print("发生未知错误：", e)

        attempts += 1
        if attempts == 1 and max_attempts == 1:
            print(f"尝试获取邮件失败，请检查邮箱。")
            return None

        print(f"第 {attempts} 次尝试获取邮件失败，将在 {retry_delay} 秒后重试...")
        time.sleep(retry_delay)

    print(f"多次尝试后仍未能获取到邮件，共尝试 {max_attempts} 次。")
    return None
def fetch_email_from_openai(username, password, frommail='com', num_emails=2):
    try:

        pop_server = 'pop-mail.outlook.com'
        pop_conn = poplib.POP3_SSL(pop_server)
        pop_conn.user(username)
        pop_conn.pass_(password)

        num_messages = len(pop_conn.list()[1])
        if num_messages == 0:
            pop_conn.quit()
            return None

        url_pattern = r'(https?://\S+)'
        for i in range(num_messages, max(0, num_messages - num_emails), -1):
            _, lines, _ = pop_conn.retr(i)
            email_content = b'\n'.join(lines)
            msg = BytesParser().parsebytes(email_content)
            from_decoded = str(make_header(decode_header(msg.get('from'))))

            if frommail in from_decoded:
                urls = []
                if msg.is_multipart():
                    for part in msg.walk():
                        content_type = part.get_content_type()
                        if content_type == "text/plain" or content_type == "text/html":
                            payload = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                            urls = re.findall(url_pattern, payload)
                            if urls:
                                break  # Found URL in one of the parts
                else:
                    payload = msg.get_payload(decode=True).decode('utf-8', errors='ignore')
                    urls = re.findall(url_pattern, payload)

                if urls:
                    # Assuming you only need the first found URL
                    # email_info = {
                    #     "主题": str(make_header(decode_header(msg.get('subject')))),
                    #     "发件人": from_decoded,
                    #     "时间": msg.get('date'),
                    #     "正文": urls[0]  # Using the first URL found
                    # }
                    # Uncomment the following line to delete the email
                    pop_conn.dele(i)
                    pop_conn.quit()
                    return urls[0]

        pop_conn.quit()
        return None
    except Exception as e:
        print(f"{e},账号被封")
        return None



if __name__ == '__main__':
    username = "dshkjhafsafkj@hotmail.com"
    email_pwd = "SgR7l6uTa"

    # print(fetch_email_from_openai(username, email_pwd))
    # print(get_signup_link(username, "SgR7l6uTa", username))
    print(get_signup_link("vileanna8959@hotmail.com", "SgR7l6uTa","adfas23eddsx@autogpt-zh.com"))

